package com.george.shartdingsphere.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * shardingsphere配置加载
 */
@Configuration
public class XmShardingConfig {

    private static final String SHARDING_DS = "shardingDatasource";

    @Bean
    public DataSource dataSource(List<DynamicDataSourceProvider> providers, ResourceLoader resourceLoader, DynamicDataSourceProperties properties)
            throws IOException, SQLException {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(providers);
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setP6spy(properties.getP6spy());
        dataSource.setSeata(properties.getSeata());
        dataSource.setGraceDestroy(properties.getGraceDestroy());
        File yamlFile = resourceLoader.getResource("classpath:shardingsphere.yaml").getFile();
        DataSource shardingsphereDateSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);
        dataSource.addDataSource(SHARDING_DS, shardingsphereDateSource);
        return dataSource;
    }
}
